import { Button, notification } from 'antd';

import { post } from '@/api';
import { useGraph } from '@/hooks/useGraph';
import { useNodeResults } from '@/store/node-results';
import { useNodeVerificationResults } from '@/store/node-verification';
import { formatEdgesForSave, formatNodesForSave, toDefaultCellStyle } from '@/utils/graph';

export interface ActionsTestRef {
  saveHandle: (onlySave?: boolean, isTest?: boolean) => Promise<void>;
}

export const ActionOfSave = memo(
  forwardRef<ActionsTestRef>((_, ref) => {
    
    const { graph } = useGraph();
    const [searchParams] = useSearchParams();
    const flowId = searchParams.get('flowId');
    const [loading, setLoading] = useState(false);
    const { clearResults } = useNodeResults();
    const verificationResults = useNodeVerificationResults();
    const resetNodeStatus = () => {
      graph?.getNodes().forEach((node) => {
        node?.setData({
          status: ''
        });
      });
    };

    const saveHandle = async (onlySave = true, isTest?: boolean) => {
      resetNodeStatus();
      toDefaultCellStyle(graph);
      clearResults();
      verificationResults.clearResults();
      
      const data = graph?.toJSON();
      if (!data) return;
      const edges = formatEdgesForSave(data.cells || []);

      const nodes = formatNodesForSave(data.cells || []);

      const resolveFinalGraphJson = () => {
        const json = graph?.toJSON();
        if (json) {
          json.cells.forEach((item) => {
            if (item.shape === 'base-edge') {
              item.attrs = { line: { strokeDasharray: '', style: { animation: '' } } };
            } else if (item.view === 'vue-shape-view') {
              delete item.data.status;
            }
          });
        }
        return json;
      };

      const newGraph = JSON.stringify(resolveFinalGraphJson());

      try {
        setLoading(true);
        await post('/flow/addGraph', {
          data: {
            flowId: +flowId!,
            graph: newGraph,
            nodes: nodes as any[],
            edges
          }
        });

        if (!isTest) {
          notification.success({
            placement: 'bottomRight',
            message: onlySave ? '保存成功' : '提交成功'
          });
        }
      } finally {
        setLoading(false);
      }
    };

    useImperativeHandle(ref, () => ({ saveHandle }));

    return (
      <Button loading={loading} type="primary" onClick={() => saveHandle()}>
        <span className="i-solar:folder-check-broken"></span>
        保存
      </Button>
    );
  })
);
